<?php

namespace App\Kuafu\Category\Controller\B;

use App\Kuafu\Category\Enum\CategoryCodeEnum;
use App\Kuafu\Category\Service\CategoryService;
use App\Kuafu\Category\Validate\CategoryValidate;
use Illuminate\Http\Request;
use App\Kuafu\Base\Controller\BaseController;

class CategoryController extends BaseController
{

    /**
     * add category
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\Category\Exceptions\CategoryException
     */
    public function addCategory(Request $request)
    {
        //参数校验
        $valid = CategoryValidate::addOrSetCategory($request);
        if ($valid) {
            return $this->fail(CategoryCodeEnum::ERR_400000, $valid);
        }
        CategoryService::addCategory($request);
        return $this->success();
    }


    /**
     * get list
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCategoryList(Request $request)
    {
        $brandId    = (int)$request->header('brandId');

        $data       = CategoryService::getCategoryList($brandId);
        $returnData = null;
        if ($data) {
            $returnData = $data->toArray();
        }
        return $this->success($returnData);
    }

    /**
     * get info
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCategoryInfo(Request $request)
    {
        if (empty($request->categoryId)) {
            return $this->fail(CategoryCodeEnum::ERR_400000);
        }
        $data = CategoryService::getCategoryInfo($request);
        if (!empty($data)) {
            $data = $data->toArray();
        }
        return $this->success($data);
    }

    /**
     * update
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\Category\Exceptions\CategoryException
     */
    public function setCategory(Request $request)
    {
        //参数校验
        $valid = CategoryValidate::addOrSetCategory($request);
        if ($valid) {
            return $this->fail(CategoryCodeEnum::ERR_400000, $valid);
        }
        CategoryService::setCategory($request);
        return $this->success();
    }

    /**
     * 软删除分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\Category\Exceptions\CategoryException
     */
    public function deleteCategory(Request $request)
    {
        $valid = CategoryValidate::getCategoryInfoById($request);
        if ($valid) {
            return $this->fail(CategoryCodeEnum::ERR_400000, $valid);
        }
        CategoryService::deleteCategory($request);
        return $this->success();
    }
}
